package com.uenpay.im.ui.old.activity.group;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.database.FriendDB;
import com.qyx.android.database.GroupMemberManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.BaseContentModel;
import com.qyx.android.protocol.SessionModel;
import com.qyx.android.weight.utils.QyxWeightDensityUtils;
import com.qyx.android.weight.view.MyListView;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ChatActivity;
import com.uenpay.im.ui.old.activity.funds.UpdateJoinGroupAmountActivity;
import com.uenpay.im.ui.old.activity.red.RedHandler;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.configuration.QYXIMConfiguration;
import com.uenpay.im.entities.SelectedFriendEntity;
import com.uenpay.im.entities.chatbean.MsgRedModel;
import com.uenpay.util.app.base.BaseActivity;

import java.util.ArrayList;
import java.util.Locale;

/**
 * @author SL
 * @created 2016-1-3 上午11:30:58
 * @copyRight http://www.qiyunxin.com
 */
public class AddGroupMemberActivity extends BaseActivity {

    private GroupMangerHandler mGroupMangerHandler = new GroupMangerHandler();
    private BaseContentModel forwardMsg;
    private HorizontalScrollView mHorizontalScrollView;
    private LinearLayout selectedUserLayout;
    private String group_id;
    private GroupMemberManager mGroupMemberManager = new GroupMemberManager();
    private ChooseGroupMemberAdapter chooseGroupMemberAdapter = null;
    private ArrayList<SelectedFriendEntity> selectedMembers = new ArrayList<SelectedFriendEntity>();
    private ArrayList<SelectedFriendEntity> selectedFriendEntities = new ArrayList<SelectedFriendEntity>();
    private MyListView pinnedListView;
    private TextView rightTextView, choose_group_tv;
    private EditText search_et;
    private ArrayList<FriendEntity> friends;
    private View loading;
    private boolean isCreateGroup = false;
    private String cust_id = "";
    private FriendEntity friend;
    private int create_group_type = GroupType.NORMAL_GROUP;
    public static AddGroupMemberActivity mAddGroupMemberActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
        mAddGroupMemberActivity = this;
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_delete_group_member_layout;
    }

    @Override
    public void initView(View view) {
        if (getIntent() != null) {
            if (getIntent().hasExtra("group_id")) {
                group_id = getIntent().getStringExtra("group_id");
                isCreateGroup = false;
            } else {
                isCreateGroup = true;
            }

            if (getIntent().hasExtra("talkId")) {
                cust_id = getIntent().getStringExtra("talkId");
                friend = FriendDB.getFriend(cust_id);
            }

            if (getIntent().hasExtra("group_type")) {
                create_group_type = getIntent().getIntExtra("group_type",
                        GroupType.NORMAL_GROUP);
            }

            Bundle bu = getIntent().getExtras();
            if (bu != null && bu.getParcelable("forwardMsg") != null) {
                forwardMsg = bu.getParcelable("forwardMsg");
            }
        }

        initView();
        initListener();
        refresh();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.add_group_member));
        rightTextView = ((TextView) findViewById(R.id.title_right_tv));
        rightTextView.setText(getResources().getString(R.string.sure));
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.selected_users_scroll);
        selectedUserLayout = (LinearLayout) findViewById(R.id.selected_users);
        pinnedListView = (MyListView) findViewById(R.id.pinnedListView);
        choose_group_tv = (TextView) findViewById(R.id.choose_group_tv);
        search_et = (EditText) findViewById(R.id.search_et);
        loading = findViewById(R.id.loading);

        if (!TextUtils.isEmpty(group_id)) {
            choose_group_tv.setVisibility(View.GONE);
            findViewById(R.id.choose_group_view).setVisibility(View.GONE);
        }

        if (create_group_type == GroupType.AMOUNT_GORUP) {
            rightTextView.setText(R.string.next);
        }
    }

    protected void initListener() {
        findViewById(R.id.back_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        finish();
                    }
                });
        findViewById(R.id.title_right_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (selectedMembers == null
                                || selectedMembers.size() <= 0) {
                            IMApplication.showToast(getResources().getString(
                                    R.string.list_is_empty));
                            return;
                        }
                        findViewById(R.id.title_right_layout).setEnabled(false);
                        if (isCreateGroup) {
                            if (selectedMembers.size() == 1
                                    && TextUtils.isEmpty(cust_id)) {
                                startTalk(
                                        selectedMembers.get(0).friend.cust_id,
                                        selectedMembers.get(0).friend.nick_name,
                                        PacketType.PERSONAL);
                            } else {
                                if (create_group_type == GroupType.AMOUNT_GORUP) {
                                    createAmountGroup();
                                } else {
                                    createGroup();
                                }
                            }
                        } else {
                            groupAddPerson();
                        }
                    }
                });

        pinnedListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        SelectedFriendEntity selected = (SelectedFriendEntity) arg0
                                .getAdapter().getItem(arg2);
                        if (selected.selectedStatus == 3)
                            return;
                        for (int i = 0; i < selectedFriendEntities.size(); i++) {
                            if (selectedFriendEntities.get(i).friend.cust_id
                                    .equals(selected.friend.cust_id)) {
                                if (selectedFriendEntities.get(i).selectedStatus == 1) {
                                    selectedFriendEntities.get(i).selectedStatus = 2;
                                } else {
                                    selectedFriendEntities.get(i).selectedStatus = 1;
                                }
                                break;
                            }
                        }
                        chooseGroupMemberAdapter.notifyDataSetChanged();
                        if (chooseGroupMemberAdapter
                                .isSelected(selected.friend.cust_id) == 2) {
                            selectedMembers.add(selected);
                            addSelectedFriend(selected.friend);
                        } else {
                            removeSelectedFriend(selected.friend.cust_id);
                            selectedMembers.remove(selected);
                        }

                        if (selectedMembers.size() < 1) {
                            rightTextView.setText(getResources().getString(
                                    R.string.sure));
                        } else {
                            rightTextView.setText(getResources().getString(
                                    R.string.sure)
                                    + "(" + selectedMembers.size() + ")");
                        }
                    }
                });
        search_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                searchTextInUsers(s);
            }
        });
        choose_group_tv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Bundle bu = new Bundle();
                bu.putParcelable("forwardMsg", forwardMsg);
                Utils.startActivityForResult(AddGroupMemberActivity.this,
                        MyGroupsActivity.class, bu, 100);
            }
        });
    }

    private void searchTextInUsers(CharSequence text) {
        if (text != null && text.length() > 0) {
            if (TextUtils.isEmpty(text)) {
                return;
            }
            ArrayList<SelectedFriendEntity> tempMembers = new ArrayList<SelectedFriendEntity>();
            for (SelectedFriendEntity mFriendEntity : selectedFriendEntities) {
                String charIndex = mFriendEntity.friend.nick_name;
                if (!TextUtils.isEmpty(mFriendEntity.friend.remarks_name)) {
                    charIndex = mFriendEntity.friend.remarks_name;
                }

                if (mFriendEntity.friend.nick_name.toLowerCase(
                        Locale.getDefault()).contains(
                        text.toString().toLowerCase(Locale.getDefault()))
                        || charIndex.contains(text.toString().toLowerCase(
                        Locale.getDefault()))) {
                    tempMembers.add(mFriendEntity);
                }
            }
            if (tempMembers.size() > 0) {
                chooseGroupMemberAdapter = new ChooseGroupMemberAdapter(
                        AddGroupMemberActivity.this, tempMembers);
                pinnedListView.setAdapter(chooseGroupMemberAdapter);
                pinnedListView.setVisibility(View.VISIBLE);
            } else {
                pinnedListView.setVisibility(View.GONE);
            }
        } else {
            pinnedListView.setVisibility(View.VISIBLE);
            chooseGroupMemberAdapter = new ChooseGroupMemberAdapter(
                    AddGroupMemberActivity.this, selectedFriendEntities);
            pinnedListView.setAdapter(chooseGroupMemberAdapter);
        }
    }

    private void removeSelectedFriend(String cust_id) {
        int pos = -1;
        for (SelectedFriendEntity friend : selectedMembers) {
            pos++;
            if (friend.friend.cust_id.equals(cust_id)) {
                break;
            }
        }

        if (pos > -1) {
            if (selectedUserLayout != null) {
                selectedUserLayout.removeViewAt(pos);
            }
            scrollToEnd();
        }
    }

    private void addSelectedFriend(FriendEntity friend) {
        MaskImageView image = new MaskImageView(AddGroupMemberActivity.this);

        LayoutParams lp = new LayoutParams(
                QyxWeightDensityUtils.dp2px(this, 35),
                QyxWeightDensityUtils.dp2px(this, 35));
        lp.setMargins(5, 0, 5, 0);
        image.setLayoutParams(lp);
        image.SetUrl(APIConfiguration.getAvatarUrlNormal(friend.cust_id,
                PacketType.PERSONAL));
        selectedUserLayout.addView(image);
        scrollToEnd();
    }

    public void scrollToEnd() {
        mHorizontalScrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mHorizontalScrollView
                        .fullScroll(HorizontalScrollView.FOCUS_RIGHT);
            }
        }, 100);
    }

    private void refresh() {
        QYXIMConfiguration.singleThreadExecutor.execute(new Runnable() {

            @Override
            public void run() {
                friends = FriendDB.getFriends();
                for (int i = 0, size = friends.size(); i < size; i++) {
                    SelectedFriendEntity selectedFriendEntity = new SelectedFriendEntity(
                            friends.get(i));
                    if (!TextUtils.isEmpty(group_id)) {
                        if (mGroupMemberManager.queryExists(
                                Long.valueOf(group_id),
                                Long.valueOf(friends.get(i).cust_id))) {
                            selectedFriendEntity.selectedStatus = 3;
                        }
                    } else {
                        if (friend != null
                                && friend.cust_id.equals(friends.get(i).cust_id)) {
                            selectedFriendEntity.selectedStatus = 3;
                        }
                    }
                    selectedFriendEntities.add(selectedFriendEntity);
                }
                myHandler.sendEmptyMessage(1);
            }
        });
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                chooseGroupMemberAdapter = new ChooseGroupMemberAdapter(
                        AddGroupMemberActivity.this, selectedFriendEntities);
                pinnedListView.setAdapter(chooseGroupMemberAdapter);
            }
            return false;
        }
    });

    private void groupAddPerson() {
        String receive_cust_id = "";
        for (int i = 0; i < selectedMembers.size(); i++) {
            if (i == selectedMembers.size() - 1) {
                receive_cust_id += selectedMembers.get(i).friend.cust_id;
            } else {
                receive_cust_id += selectedMembers.get(i).friend.cust_id + ",";
            }
        }
        loading.setVisibility(View.VISIBLE);
        mGroupMangerHandler.addGroupMembers(create_group_type, group_id,
                receive_cust_id, new GroupMangerHandler.IGroupResultListener() {

                    @Override
                    public void onGroupResult(int status, String msg) {
                        myHandler.sendEmptyMessage(0);
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            setResult(RESULT_OK);
                            finish();
                        } else if (!TextUtils.isEmpty(msg)) {
                            IMApplication.showToast(msg);
                        }
                        findViewById(R.id.title_right_layout).setEnabled(true);
                    }
                });
    }

    private void createGroup() {
        String receive_cust_id = "";
        if (!TextUtils.isEmpty(cust_id)) {
            SelectedFriendEntity entity = new SelectedFriendEntity(friend);
            entity.selectedStatus = 2;
            selectedMembers.add(0, entity);
        }
        String groupName = "";
        for (int i = 0; i < selectedMembers.size(); i++) {
            if (i < 3) {
                if (TextUtils.isEmpty(groupName)) {
                    groupName = selectedMembers.get(i).friend.nick_name;
                } else {
                    groupName = groupName + ","
                            + selectedMembers.get(i).friend.nick_name;
                }
            }
            if (i == selectedMembers.size() - 1) {
                receive_cust_id += selectedMembers.get(i).friend.cust_id;
            } else {
                receive_cust_id += selectedMembers.get(i).friend.cust_id + ",";
            }
        }

        loading.setVisibility(View.VISIBLE);
        final String chatName = groupName;
        mGroupMangerHandler.createGroup(groupName, receive_cust_id, "",
                new GroupMangerHandler.IGroupManagerResultListener() {

                    @Override
                    public void onGroupManagerResult(int status, String msg,
                                                     String chatId) {
                        myHandler.sendEmptyMessage(0);
                        if (!TextUtils.isEmpty(msg)) {
                            IMApplication.showToast(msg);
                        }
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            if (forwardMsg != null
                                    && forwardMsg.getType() == MsgContentType.RED) {
                                sendRed(chatId, chatName);
                            } else {
                                startTalk(chatId, chatName, PacketType.GROUP);
                            }
                        } else {
                            findViewById(R.id.title_right_layout).setEnabled(
                                    true);
                        }
                    }
                });

    }

    private void createAmountGroup() {
        // String groupName = "";
        String receive_cust_id = "";
        for (int i = 0; i < selectedMembers.size(); i++) {
            // if (i < 3) {
            // if (TextUtils.isEmpty(groupName)) {
            // groupName = selectedMembers.get(i).friend.nick_name;
            // } else {
            // groupName = groupName + ","
            // + selectedMembers.get(i).friend.nick_name;
            // }
            // }
            if (i == selectedMembers.size() - 1) {
                receive_cust_id += selectedMembers.get(i).friend.cust_id;
            } else {
                receive_cust_id += selectedMembers.get(i).friend.cust_id + ",";
            }
        }
        Intent intent = new Intent(AddGroupMemberActivity.this,
                UpdateJoinGroupAmountActivity.class);
        intent.putExtra("cust_ids", receive_cust_id);
        intent.putExtra("chat_name",
                getResources().getString(R.string.funds_group));
        startActivity(intent);
        findViewById(R.id.title_right_layout).setEnabled(true);
    }

    private RedHandler mRedHandler = new RedHandler();

    private void sendRed(final String chatid, final String chatName) {
        loading.setVisibility(View.VISIBLE);
        String red_packet_id = "";
        MsgRedModel msgRedModel = (MsgRedModel) forwardMsg;
        if (msgRedModel != null) {
            red_packet_id = msgRedModel.getPacketsid();
        }
        mRedHandler.sendRed(red_packet_id, chatid, PacketType.GROUP,
                new RedHandler.ISendRedResult() {

                    @Override
                    public void onSendResult(int status, String reason) {
                        loading.setVisibility(View.GONE);
                        if (status == HttpInvokeResultCode.RESULT_OK)
                            startTalk(chatid, chatName, PacketType.GROUP);
                        else if (!TextUtils.isEmpty(reason)) {
                            IMApplication.showToast(reason);
                        }
                    }
                });
    }

    private void startTalk(String chat_id, String chat_name, int chatType) {

        Bundle bu = new Bundle();
        SessionModel sessionModel = new SessionModel();
        sessionModel.setSessionId(Long.valueOf(chat_id));
        sessionModel.setSessionType(chatType);
        bu.putParcelable("session", sessionModel);
        bu.putString("stranger_name", chat_name);
        Intent intent = new Intent();
        intent.putExtras(bu);
        // Intent intent = new Intent(AddGroupMemberActivity.this,
        // ChatActivity.class);
        // i

        if (forwardMsg != null) {
            // bu.putParcelable("forwardMsg", forwardMsg);
            // TODO
            setResult(RESULT_OK, intent);
        } else {
            intent.setClass(AddGroupMemberActivity.this, ChatActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            IMApplication.IS_REFRESH_TOP_MSG = true;
        }

        finish();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {
            SessionModel sessionModel = (SessionModel) data
                    .getParcelableExtra("session");
            String stranger_name = data.getStringExtra("stranger_name");
            startTalk(sessionModel.getSessionId() + "", stranger_name,
                    PacketType.GROUP);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
